import requests
import json
import time
from typing import Dict, Optional, List
from django.conf import settings

class AmapService:
    """高德地图API服务"""
    
    def __init__(self, api_key: str = None):
        """
        初始化高德地图服务
        
        Args:
            api_key: 高德地图Web服务API密钥
        """
        self.api_key = api_key or getattr(settings, 'AMAP_API_KEY', '')
        self.base_url = "https://restapi.amap.com/v3"
        
    def reverse_geocode(self, longitude: float, latitude: float) -> Optional[Dict]:
        """
        逆地理编码：将坐标转换为地址信息
        
        Args:
            longitude: 经度
            latitude: 纬度
            
        Returns:
            地址信息字典，包含省市区等详细信息
        """
        if not self.api_key:
            return None
            
        url = f"{self.base_url}/geocode/regeo"
        params = {
            'key': self.api_key,
            'location': f"{longitude},{latitude}",
            'extensions': 'all',
            'output': 'json'
        }
        
        try:
            response = requests.get(url, params=params, timeout=5)
            if response.status_code == 200:
                data = response.json()
                if data.get('status') == '1':
                    return data.get('regeocode', {})
            return None
        except Exception as e:
            print(f"高德地图API调用失败: {e}")
            return None
    
    def get_address_components(self, longitude: float, latitude: float) -> Dict:
        """
        获取地址组件信息
        
        Args:
            longitude: 经度
            latitude: 纬度
            
        Returns:
            地址组件字典
        """
        regeocode_data = self.reverse_geocode(longitude, latitude)
        if not regeocode_data:
            return {
                'province': '',
                'city': '',
                'district': '',
                'street': '',
                'address': '',
                'formatted_address': ''
            }
        
        address_component = regeocode_data.get('addressComponent', {})
        
        return {
            'province': address_component.get('province', ''),
            'city': address_component.get('city', ''),
            'district': address_component.get('district', ''),
            'street': address_component.get('township', ''),
            'address': regeocode_data.get('formatted_address', ''),
            'formatted_address': regeocode_data.get('formatted_address', '')
        }
    
    def get_location_name(self, longitude: float, latitude: float) -> str:
        """
        获取地点名称
        
        Args:
            longitude: 经度
            latitude: 纬度
            
        Returns:
            地点名称字符串
        """
        components = self.get_address_components(longitude, latitude)
        
        # 构建地点名称
        parts = []
        if components['district']:
            parts.append(components['district'])
        if components['street']:
            parts.append(components['street'])
        
        if parts:
            return ''.join(parts)
        elif components['formatted_address']:
            return components['formatted_address']
        else:
            return f"未知地点({longitude}, {latitude})"
    
    def batch_get_location_names(self, coordinates: List[tuple]) -> Dict[str, str]:
        """
        批量获取地点名称
        
        Args:
            coordinates: 坐标列表，格式为 [(lng, lat), ...]
            
        Returns:
            坐标到地点名称的映射字典
        """
        result = {}
        
        for lng, lat in coordinates:
            location_name = self.get_location_name(lng, lat)
            coord_key = f"{lng}_{lat}"
            result[coord_key] = location_name
            
            # 添加延迟避免API限制
            time.sleep(0.1)
        
        return result

# 全局实例
amap_service = AmapService() 